<?php
// tell PHP to log errors to ipn_errors.log in this directory
ini_set('log_errors', true);
ini_set('error_log', dirname(__FILE__).'/ipn_errors.log');

// intantiate the IPN listener
include('ipnlistener.php');
$listener = new IpnListener();

// tell the IPN listener to use the PayPal test sandbox
$listener->use_sandbox = false;

// try to process the IPN POST
try {
    $listener->requirePostMethod();
    $verified = $listener->processIpn();
} catch (Exception $e) {
    error_log($e->getMessage());
    exit(0);
}

// TODO: Handle IPN Response here
if ($verified) {

    $errmsg = '';   // stores errors from fraud checks
    
    // 1. Make sure the payment status is "Completed" 
    if ($_POST['payment_status'] != 'Completed') { 
        // simply ignore any IPN that is not completed
        exit(0); 
    }

    // 2. Make sure seller email matches your primary account email.
    if ($_POST['receiver_email'] != 'emil@emildayan.se') {
        $errmsg .= "'receiver_email' does not match: ";
        $errmsg .= $_POST['receiver_email']."\n";
    }
    
    // 3. Make sure the amount(s) paid match
    if ($_POST['mc_gross'] != '5.00') {
        $errmsg .= "'mc_gross' does not match: ";
        $errmsg .= $_POST['mc_gross']."\n";
    }
    
    // 4. Make sure the currency code matches
    if ($_POST['mc_currency'] != 'USD') {
        $errmsg .= "'mc_currency' does not match: ";
        $errmsg .= $_POST['mc_currency']."\n";
    }

   // 5. Ensure the transaction is not a duplicate.
    $txn_id = mysql_real_escape_string($_POST['txn_id']);
	$exist = safe_query(mysql_fetch_array("SELECT * FROM ".PREFIX."orders WHERE txn_id = '".$txn_id."'"));
	if($exist)
		$errmsg .= "'txn_id' has already been processed: ".$_POST['txn_id']."\n";
	

    
    if (!empty($errmsg)) {
    
        // manually investigate errors from the fraud checking
        $body = "IPN failed fraud checks: \n$errmsg\n\n";
        $body .= $listener->getTextReport();
        mail('emil@emildayan.se', 'IPN Fraud Warning', $body);
        
    } else {
	 $body = "IPN Success\n\n";
        $body .= $listener->getTextReport();
    mail('emil@emildayan.se', 'Valid IPN', $body);
        // add this order to a table of completed orders
    $payer_email = mysql_real_escape_string($_POST['payer_email']);
    $mc_gross = mysql_real_escape_string($_POST['mc_gross']);
	safe_query("INSERT INTO ".PREFIX."orders VALUES ('".$txn_id."', '".$payer_email."', '".$mc_gross."'");

    // send user an email with a link to their digital download
    $to = filter_var($_POST['payer_email'], FILTER_SANITIZE_EMAIL);
    $subject = "Betfor5 Purchase";
    mail($to, "BetFor5 Success", "blabla");
    }
    
} else {
    // manually investigate the invalid IPN
    mail('emil@emildayan.se', 'Invalid IPN', $listener->getTextReport());
}

// ...
?>